<?php
/**
 * Created by PhpStorm.
 * User: camfee<camfee@foxmail.com>
 * Date: 2017/9/29
 * Time: 16:59
 */
define('SITE_AUTH', 'user-gold-coinLog');
require('../../../common.inc.php');
require_once(ROOT_PATH . 'framework/config/mobileapi/base.cfg.php');


use lib\core\AdminAction;
use Center\CoinLog as CCoinLog;
use Center\User as CUser;
use Common\Bridge;

class coinLog extends AdminAction
{
    private $type = CCoinLog::TYPE_LIST;

    private $type_list = [
        'coin_type_1',
        'coin_type_2',
        'coin_type_100',
        'coin_type_101',
        'coin_type_102',
        'coin_type_103',
        'coin_type_104',
        'coin_type_105',
        'coin_type_106',
        'coin_type_107',
        'coin_type_ios_1',
        'coin_type_ios_2',
        'coin_type_ios_100',
        'coin_type_ios_101',
        'coin_type_ios_102',
        'coin_type_ios_103',
        'coin_type_ios_104',
        'coin_type_ios_105',
        'coin_type_ios_106',
        'coin_type_ios_107',
        'coin_type_adr_1',
        'coin_type_adr_2',
        'coin_type_adr_100',
        'coin_type_adr_101',
        'coin_type_adr_102',
        'coin_type_adr_103',
        'coin_type_adr_104',
        'coin_type_adr_105',
        'coin_type_adr_106',
        'coin_type_adr_107',
    ];

    public function doDefault()
    {
        $smarty = $this->app->page();
        // 列表
        $where = ['CoinLogId >' => 0];
        $s_userid = !empty($_GET['s_userid']) ? (int)$_GET['s_userid'] : '';
        $s_mobile = trim($_GET['s_mobile']);
        if (empty($s_userid) && $s_mobile) {
            $s_user = CUser::getList([CUser::FIELD_MOBILE => $s_mobile], 0, 1);
            if (!empty($s_user['data'][0])) {
                $s_userid = $s_user['data'][0]['UserId'];
            }
        }
        if ($s_userid) {
            $where += ['UserId' => $s_userid];
        }
        $s_shopid = intval($_GET['s_shopid']);
        if ($s_shopid) {
            $where += ['Info' => $s_shopid];
        }
        $s_type = intval($_GET['s_type']);
        if ($s_type) {
            $where += ['Type' => $s_type];
        }
        $start_time = trim($_GET['start_time']);
        if ($start_time) {
            $where += ['CreateTime >=' => $start_time];
        }
        $end_time = trim($_GET['end_time']);
        if ($end_time) {
            $where += ['CreateTime <=' => $end_time];
        }
        $s_data = [
            's_userid' => $s_userid,
            's_mobile' => $s_mobile,
            's_type' => $s_type,
            's_start_time' => $start_time,
            's_end_time' => $end_time,
        ];

        if (!empty($_GET['exportExcel'])) {
            $data = CCoinLog::getList($where, 0, 0);
            set_time_limit(0);
            if (!empty($data['data'])) {
                $user_id = [];
                foreach ($data['data'] as $k => $v) {
                    $user_id[$v['UserId']] = $v['UserId'];
                }
                $user_data = CUser::getInfoByIds($user_id);
                $user = [];
                foreach ($user_data as $k => $v) {
                    $user[$v['UserId']] = !empty($v['Mobile']) ? $v['Mobile'] : $v['UserNick'];
                }
            }
            $filename = mb_convert_encoding('用户金果记录-' . date("YmdHis"), "GB2312", "UTF-8");
            $filename_type = 'xls';
            header("Content-type:application/vnd.ms-excel");
            Header("Accept-Ranges:bytes");
            Header("Content-Disposition:attachment;filename=" . $filename . "." . $filename_type);  //$filename导出的文件名
            header("Pragma: no-cache");
            header("Expires: 0");
            $excel_str = '';
            if ($filename_type == 'xls') {
                $excel_str = <<<EOT
            <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
             <head>
              <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
              <meta http-equiv=Content-Type content="text/html; charset=gb2312">
              <!--[if gte mso 9]><xml>
              <x:ExcelWorkbook>
              <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                <x:Name></x:Name>
                <x:WorksheetOptions>
                  <x:DisplayGridlines/>
                </x:WorksheetOptions>
                </x:ExcelWorksheet>
              </x:ExcelWorksheets>
              </x:ExcelWorkbook>
              </xml><![endif]-->
             </head>
EOT;
            }
            $excel_str .= '<table>';
            $excel_str .= '<tr><td>记录ID</td><td>用户ID</td><td>昵称</td><td>记录类型</td><td>金果数</td><td>创建时间</td></tr>';
            foreach ($data['data'] as $k => $v) {
                $excel_str .= "<tr><td style='vnd.ms-excel.numberformat:@'>{$v['CoinLogId']}</td><td style='vnd.ms-excel.numberformat:@'>{$v['UserId']}</td><td>{$user[$v['UserId']]}</td><td>{$this->type[$v['Type']]}</td><td>{$v['CoinNum']}</td><td>{$v['CreateTime']}</td></tr>";
            }
            $excel_str .= '</table>';
            echo mb_convert_encoding($excel_str, "GB2312", "UTF-8");
            exit();
        }

        $page = $_GET['page'] < 1 ? 1 : (int)$_GET['page'];
        $limit = parent::PAGE_SIZE;
        $offset = ($page - 1) * $limit;

        $data = CCoinLog::getList($where, $offset, $limit);
        $count = $data['count'];
        if ($count > 0) {
            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            if (!empty($data['data'])) {
                $user_id = $shop_id = [];
                foreach ($data['data'] as $k => $v) {
                    $user_id[$v['UserId']] = $v['UserId'];
                    if (!empty($v['Info']) && is_numeric($v['Info'])) {
                        $shop_id[$v['Info']] = $v['Info'];
                    }
                }
                $user_data = CUser::getInfoByIds($user_id);
                $user = [];
                foreach ($user_data as $k => $v) {
                    $user[$v['UserId']] = !empty($v['Mobile']) ? $v['Mobile'] : $v['UserNick'];
                }
                $smarty->value('user', $user);
                $shop_data = \Center\Shop::getInfoByIds($shop_id);
                $shop = [];
                foreach ($shop_data as $k => $v) {
                    $shop[$v['Id']] = trim($v['Name']);
                }
                $smarty->value('shop', $shop);
            }
            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('page_info', $page_info);
            $smarty->value('pagination', $pagination);
            $smarty->value('list', $data['data']);
        }
        $smarty->value('type', $this->type);
        $smarty->value('s_data', $s_data);
        $smarty->output('gold/coinLog_list.tpl');
    }

    public function doStatistic()
    {
        $smarty = $this->app->page();
        // 所有端总统计
        $ios_sum = $android_sum = $all_sum = [
            'all' => [//'all' => 0,
            ],
            'last_month' => [//'all' => 0,
            ],
            'month' => [//'all' => 0,
            ],
            'last_week' => [//'all' => 0,
            ],
            'week' => [//'all' => 0,
            ],
            'yesterday' => [//'all' => 0,
            ],
            'day' => [//'all' => 0,
            ]
        ];
        foreach ($all_sum as $k => $v) {
            foreach ($this->type as $k1 => $v1) {
                $all_sum[$k][$k1] = 0;
                $ios_sum[$k][$k1] = 0;
                $android_sum[$k][$k1] = 0;
            }
        }
        //---------------------------------------------------------------------------
        //当日流水总额
        //$this->groupData($all_sum, 'day', $now_day, 0);
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        $select_sql = "SELECT SUM(`CoinNum`) AS Total,`Type` FROM `CoinLog` WHERE CreateTime >= '" . $start . "' AND `CreateTime` <= '" . $end . "' GROUP BY `Type`";
        $type_num = $this->readDb($select_sql);
        $today_total = $type_nums = [];
        foreach ($type_num as $v) {
            $type_nums[$v['Type']] = $v['Total'];
        }
        //ios
        $select_sql = "SELECT SUM(`CoinNum`) AS Total,`Type` FROM `CoinLog` WHERE AppId = 10 AND CreateTime >= '" . $start . "' AND `CreateTime` <= '" . $end . "' GROUP BY `Type`";
        $type_num2 = $this->readDb($select_sql);
        $today_total2 = $type_nums2 = [];
        foreach ($type_num2 as $v) {
            $type_nums2[$v['Type']] = $v['Total'];
        }
        //android
        $select_sql = "SELECT SUM(`CoinNum`) AS Total,`Type` FROM `CoinLog` WHERE AppId = 50 AND CreateTime >= '" . $start . "' AND `CreateTime` <= '" . $end . "' GROUP BY `Type`";
        $type_num3 = $this->readDb($select_sql);
        $today_total3 = $type_nums3 = [];
        foreach ($type_num3 as $v) {
            $type_nums3[$v['Type']] = $v['Total'];
        }

        foreach ($this->type as $type => $desc) {
            if (isset($type_nums[$type])) {
                $today_total[$type] = $type_nums[$type];
            } else {
                $today_total[$type] = 0;
            }
            if (isset($type_nums2[$type])) {
                $today_total2[$type] = $type_nums2[$type];
            } else {
                $today_total2[$type] = 0;
            }
            if (isset($type_nums3[$type])) {
                $today_total3[$type] = $type_nums3[$type];
            } else {
                $today_total3[$type] = 0;
            }
        }
        foreach ($all_sum as $k => $v) {
            foreach ($v as $k1 => $v1) {
                if (!in_array($k, ['yesterday', 'last_week', 'last_month'])) {
                    $all_sum[$k][$k1] = $today_total[$k1];
                    $ios_sum[$k][$k1] = $today_total2[$k1];
                    $android_sum[$k][$k1] = $today_total3[$k1];
                }
            }
        }
        //---------------------------------------------------------------------------
        //总流水额
        $this->groupData($all_sum, 'all', 0, 0);
        // ios
        $this->groupData($ios_sum, 'all', 0, 0, MOBILE_APPID_IPHONE);
        // android
        $this->groupData($android_sum, 'all', 0, 0, MOBILE_APPID_ANDROID);
        //---------------------------------------------------------------------------
        //上月流水总额
        $last_month = date('Y-m-01', strtotime('-1 month'));
        $now_month = date('Y-m-01');
        $this->groupData($all_sum, 'last_month', $last_month, $now_month);
        // ios
        $this->groupData($ios_sum, 'last_month', $last_month, $now_month, MOBILE_APPID_IPHONE);
        // android
        $this->groupData($android_sum, 'last_month', $last_month, $now_month, MOBILE_APPID_ANDROID);
        //---------------------------------------------------------------------------
        //当月流水总额
        $this->groupData($all_sum, 'month', $now_month, 0);
        // ios
        $this->groupData($ios_sum, 'month', $now_month, 0, MOBILE_APPID_IPHONE);
        // android
        $this->groupData($android_sum, 'month', $now_month, 0, MOBILE_APPID_ANDROID);
        //---------------------------------------------------------------------------
        //上周流水总额
        $timestamp = time();
        $last_week_monday = date('Y-m-d', strtotime("last week Monday", $timestamp));
        $this_week_monday = date('Y-m-d', strtotime("this week Monday", $timestamp));
        $this->groupData($all_sum, 'last_week', $last_week_monday, $this_week_monday);
        // ios
        $this->groupData($ios_sum, 'last_week', $last_week_monday, $this_week_monday, MOBILE_APPID_IPHONE);
        // android
        $this->groupData($android_sum, 'last_week', $last_week_monday, $this_week_monday, MOBILE_APPID_ANDROID);
        //---------------------------------------------------------------------------
        //本周流水总额
        $this->groupData($all_sum, 'week', $this_week_monday, 0);
        // ios
        $this->groupData($ios_sum, 'week', $this_week_monday, 0, MOBILE_APPID_IPHONE);
        // android
        $this->groupData($android_sum, 'week', $this_week_monday, 0, MOBILE_APPID_ANDROID);
        //---------------------------------------------------------------------------
        //昨日流水总额
        $now_day = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $this->groupData($all_sum, 'yesterday', $yesterday, $now_day);
        // ios
        $this->groupData($ios_sum, 'yesterday', $yesterday, $now_day, MOBILE_APPID_IPHONE);
        // android
        $this->groupData($android_sum, 'yesterday', $yesterday, $now_day, MOBILE_APPID_ANDROID);
        //---------------------------------------------------------------------------
        $smarty->value('type', $this->type);
        $smarty->value('all_sum', $all_sum);
        $smarty->value('ios_sum', $ios_sum);
        $smarty->value('android_sum', $android_sum);
        $smarty->output('gold/coinLog_statistic.tpl');
    }

    private function groupData(&$sum, $key, $start_time, $end_time, $app_id = 0)
    {
        $group_type = " GROUP BY Type";

        $time_where = "";
        if (!empty($start_time)) {
            $time_where .= " AND CreateDate >= '$start_time'";
        }
        if (!empty($end_time)) {
            $time_where .= " AND  CreateDate < '$end_time'";
        }

        $rel = $this->readAdmin($this->sum_sql('Type') . $time_where . $group_type);
        if (!empty($rel)) {
            foreach ($rel as $k => $v) {
                if (empty($app_id) && strpos($v['Type'], 'coin_type_ios_') === false && strpos($v['Type'], 'coin_type_adr_') === false) {
                    $v['Total'] = (int)$v['Total'];
                    $sum[$key][str_replace('coin_type_', '', $v['Type'])] += $v['Total'];
                } elseif ($app_id == MOBILE_APPID_IPHONE && strpos($v['Type'], 'coin_type_ios_') !== false) {
                    $v['Total'] = (int)$v['Total'];
                    $sum[$key][str_replace('coin_type_ios_', '', $v['Type'])] += $v['Total'];
                } elseif ($app_id == MOBILE_APPID_ANDROID && strpos($v['Type'], 'coin_type_adr_') !== false) {
                    $v['Total'] = (int)$v['Total'];
                    $sum[$key][str_replace('coin_type_adr_', '', $v['Type'])] += $v['Total'];
                }
            }
        }
    }

    private function sum_sql($filed)
    {
        return "SELECT $filed,SUM(Num) AS `Total` FROM SiteStatus WHERE `Type` IN (" . '"' . implode('","', $this->type_list) . '"' . ") ";
    }


    private $pdo_admin_r;

    /**
     * 读取数据库
     */
    private function readAdmin($sql)
    {
        $pdo = $this->pdo_admin_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_admin_r = Bridge::pdo(Bridge::DB_ADMIN_R);
        }
        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }

    private $pdo_r;

    /**
     * 读取数据库
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_R);
        }
        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }
}

$app->run();